package cloudPayAdmin.admin.controller.hicatcard.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.card.TCard;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.card.TCardService;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUser;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCard;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCardRecharge;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCardRechargeNewUser;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCardService;
import cloudPayAdmin.admin.entity.excel.UserRechargeImport;
import cloudPayAdmin.admin.service.hicatcard.card.CardService;
import cloudPayAdmin.admin.service.hicatcard.card.CardServiceService;
import cloudPayAdmin.admin.service.hicatcard.user.UserCardRechargeNewUserService;
import cloudPayAdmin.admin.service.hicatcard.user.UserCardRechargeService;
import cloudPayAdmin.admin.service.hicatcard.user.UserCardService;
import cloudPayAdmin.admin.service.hicatcard.user.UserService;
import cloudPayAdmin.util.AdminLteDataTableResp;
import cloudPayAdmin.util.AdminLteUtil;
import cloudPayAdmin.util.IdGenerator;
import cloudPayAdmin.util.POIExcelUtils;
import cloudPayAdmin.util.TimeUtil;
import cloudPayAdmin.util.WebUtil;
import cloudPayAdmin.util.pagebean.HqlPageBeanHelper;
import cloudPayAdmin.util.pagebean.HqlParam;
import cloudPayAdmin.util.pagebean.PageBean;

@Controller
@RequestMapping("/hicatcard/userCardRecharge")
public class UserCardRechargeController {
	
	@Autowired
	HqlPageBeanHelper hqlPageBeanHelper;

	@PersistenceContext(unitName = "entityManagerFactory")
	EntityManager entityManager;
	
	@Autowired
	Environment env;
	
	@Autowired
	CardService cardService;
	
	@Autowired
	UserCardService userCardService;
	
	@Autowired
	UserService userService;
	@Autowired
	CardServiceService cardServiceService;
	@Autowired
	UserCardRechargeService userCardRechargeService;
	@Autowired
	UserCardRechargeNewUserService userCardRechargeNewUserService;
	
	@RequestMapping(value = "/toUserCardRechargeListPage")
	public String toUserCardRechargeListPage(HttpServletRequest request, Map<String, Object> model) {		
		return "hicatcard/userCardRecharge/user-card-recharge-list";
	}
	
	@RequestMapping(value = "/toUserCardRechargeRecordListPage")
	public String toListPage(HttpServletRequest request, Map<String, Object> model) {
		request.setAttribute("statusMap", TUserCard.initStatusMap());
		return "hicatcard/user/user-card-recharge-list";
	}
	
	@RequestMapping(value = "/getUserCardRechargeListData")
	@ResponseBody
	public String getUserCardRechargeListData(HttpServletRequest request,Long userCardId,String systemPresentCardNumber) {
		
		Map<String, Object> paramMap = WebUtil.getSearchParam(request);		
		paramMap = WebUtil.formatDateRange(paramMap, TimeUtil.DATE_PATTERN_NOSEPARTOR);
		// 需要映射的实体类
		HqlParam hqlParam = WebUtil.buildHqlParam(paramMap, TUserCardRecharge.class, request);
		PageBean<TUserCardRecharge> cloudpayCardPage = hqlPageBeanHelper.findHqlPageBean(entityManager, hqlParam);			
		AdminLteDataTableResp<TUserCardRecharge> resp = AdminLteUtil.pageBeanToAdminLteDataTableResp(cloudpayCardPage,request);
		return resp.toAdminLteJsonString(TUserCardRecharge.class);
	}
	
	/**
	 * 跳转到 公司赠送卡片页面
	 * @return
	 */
	@RequestMapping("/toEditUserCardRechargePage")
	public String toCompanyPresentCardPage(HttpServletRequest request) {
		List<TCard> cardList = cardService.findAll();
		request.setAttribute("cardList", cardList);
		return "/hicatcard/userCardRecharge/user-card-recharge-edit";
	}
	
	/**
	 * 赠送卡片
	 * @param request
	 * @param phone
	 * @param presentCount
	 * @param cardId
	 * @return
	 */
	@RequestMapping("/doUserCardRecharge")
	public String companyPresentCard(HttpServletRequest request,Long[] userIds,String remark, MultipartFile userFile) {
		
		//如果不是批量导入
		if(userFile == null || StringUtils.isEmpty(userFile.getOriginalFilename())) {
			if(userIds != null && userIds.length > 0) {
				Map<String,Object> presentItemMap = WebUtils.getParametersStartingWith(request, "cardCount_");
				userCardService.companyPresentCard(userIds, presentItemMap,remark);
			}
		} else {
			List<UserRechargeImport> importList = POIExcelUtils.excelToObject(userFile, UserRechargeImport.class, 0);
			
			//先保存 userCardRecharge记录
			TUserCardRecharge userCardRecharge = new TUserCardRecharge();
			userCardRecharge.setRechargeUserCount(importList.size());
			userCardRecharge.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
			userCardRecharge.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
			userCardRecharge.setRemark(remark);
			
			Map<String,Object> presentItemMap = WebUtils.getParametersStartingWith(request, "cardCount_");
			StringBuilder rechargeContent = new StringBuilder();
			
			for (Map.Entry<String, Object> entry : presentItemMap.entrySet()) {  
				
				if(StringUtils.isNotEmpty(String.valueOf(entry.getValue()))) {
					TCard card = cardService.findById(Long.parseLong(entry.getKey()));
					String cardName = card.getCardName();
					rechargeContent.append(cardName).append((String.valueOf(entry.getValue()))).append("张,");
				}	
			} 
			
			userCardRecharge.setRechargeContent(rechargeContent.substring(0, rechargeContent.length() - 1));
			
			userCardRecharge = userCardRechargeService.save(userCardRecharge);
			
			List<TUserCard> userCardList = new ArrayList<TUserCard>();
			List<TUserCardService> userCardServiceList = new ArrayList<TUserCardService>();
			List<TUserCardRechargeNewUser> userCardRechargeNewUserList = new ArrayList<TUserCardRechargeNewUser>();
			
			for(UserRechargeImport userImport : importList) {
				List<TUser> users = userService.findByPhone(userImport.getPhone());
			
				//如果导入的是旧用户，按照原逻辑操作
				if(CollectionUtils.isNotEmpty(users)) {
					
					userCardList.clear();
					
					TUser user = users.get(0);
					
					for (Map.Entry<String, Object> entry : presentItemMap.entrySet()) {
						
						if(StringUtils.isNotEmpty(String.valueOf(entry.getValue()))) {
							Long cardId = Long.parseLong(entry.getKey());
							TCard card = cardService.findById(cardId);
							Integer count = Integer.parseInt(String.valueOf(entry.getValue()));
							
							for(int i=0;i<count;i++) {
								TUserCard userCard = new TUserCard();
								userCard.setUserId(user.getUserId());
								userCard.setCardId(cardId);
								userCard.setUserCardNumber(IdGenerator.generateOrderId(IdGenerator.ORDERID_PREFIX_USER_CARD, "00", "0000"));
								userCard.setSource(TUserCard.SOURCE_COMPANY_PRESENT);
								userCard.setSourceUserId(null);
								userCard.setStatus(TUserCard.STATUS_ACTIVE);
								userCard.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
								userCard.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
								userCard.setUserCardRechargeId(userCardRecharge.getUserCardRechargeId());
								Integer effectiveDay = card.getEffectiveDay();
								String endTime = TimeUtil.getFormatTime(TimeUtil.addDateNDay(new Date(),effectiveDay), TimeUtil.DATE_PATTERN_NOSEPARTOR);
								endTime = StringUtils.substring(endTime, 0, endTime.length() - 6) + "235959";						
								userCard.setEndTime(endTime);
								userCardList.add(userCard);
							}
							
						}
					}
					
					userCardList = userCardService.save(userCardList);
					
					for(TUserCard userCard : userCardList) {
						List<TCardService> cardServiceList = cardServiceService.findByCardId(userCard.getCardId());
						for(TCardService cardService : cardServiceList) {
							TUserCardService userCardService = new TUserCardService();
							userCardService.setUserCardId(userCard.getUserCardId());
							userCardService.setServiceId(cardService.getServiceId());
							userCardService.setServiceTime(cardService.getServiceTime());
							userCardService.setStatus("1");
							userCardService.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
							userCardService.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
							userCardService.setEnable(true);
							userCardServiceList.add(userCardService);
						}
					}
					
					
				} else {    //新用户，按照新逻辑，放入 临时表
					
					for (Map.Entry<String, Object> entry : presentItemMap.entrySet()) {
						
						if(StringUtils.isNotEmpty(String.valueOf(entry.getValue()))) {
							Long cardId = Long.parseLong(entry.getKey());
							//TCard card = cardService.findById(cardId);
							Integer count = Integer.parseInt(String.valueOf(entry.getValue()));
							
							
							TUserCardRechargeNewUser userCardRechargeNewUser = new TUserCardRechargeNewUser();
							userCardRechargeNewUser.setUserCardRecharegeId(userCardRecharge.getUserCardRechargeId());
							userCardRechargeNewUser.setPhone(StringUtils.trim(userImport.getPhone()));
							userCardRechargeNewUser.setCardId(cardId);
							userCardRechargeNewUser.setNumber(count);
							userCardRechargeNewUser.setRemark(remark);
							userCardRechargeNewUser.setStatus(TUserCardRechargeNewUser.STATUS_NOT_GET);
							userCardRechargeNewUser.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
							userCardRechargeNewUser.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
							userCardRechargeNewUserList.add(userCardRechargeNewUser);
						}			
					}
				}
			
			}
			
			userCardService.saveUserCardListAndUserCardServiceList(null, userCardServiceList);
			userCardRechargeNewUserService.save(userCardRechargeNewUserList);
		}
		
		
		return "redirect:/hicatcard/userCardRecharge/toUserCardRechargeListPage";
		
	}
	
	/**
	 * 跳转到查看详情页面
	 * @return
	 */
	@RequestMapping("/toUserCardRechargeDetailPage")
	public String toUserCardRechargeDetailPage(HttpServletRequest request,Long userCardRechargeId) {
		
		TUserCardRecharge userCardRecharge = userCardService.findUserRechargeById(userCardRechargeId);
		
		List<TUserCard> userCardList = userCardService.findByUserCardRechargeId(userCardRechargeId);
		Set<Long> userIds = new HashSet<Long>();
		for(TUserCard userCard : userCardList)  {
			userIds.add(userCard.getUserId());
		}
		
		List<TUser> userList = userService.findByIds(userIds);
		request.setAttribute("userList", userList);
		request.setAttribute("rechargeContent", StringUtils.replace(userCardRecharge.getRechargeContent(), ",", "</br>"));
		return "/hicatcard/userCardRecharge/user-card-recharge-detail";
	}
	
}
